package com.example.viewdemo.databaseTest

import android.annotation.SuppressLint
import android.content.ContentValues
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.viewdemo.R

class DatabaseTest : AppCompatActivity(), View.OnClickListener {
    private lateinit var createDatabase: Button // 声明为类的成员变量
    private lateinit var addData: Button // 声明为类的成员变量
    private lateinit var dbHelper: MyDatabaseHelper // 声明为类的成员变量
    private lateinit var updateData: Button
    private lateinit var deleteData: Button
    private lateinit var queryData: Button
    private lateinit var replaceData: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_database_test)
        createDatabase=findViewById<Button>(R.id.createDatabaseBtn)
        addData=findViewById<Button>(R.id.addData)
        updateData=findViewById<Button>(R.id.updateData)
        deleteData=findViewById<Button>(R.id.deleteData)
        queryData=findViewById<Button>(R.id.queryData)
        replaceData=findViewById<Button>(R.id.replaceData)

        createDatabase.setOnClickListener(this )
        addData.setOnClickListener(this)
        updateData.setOnClickListener(this)
        deleteData.setOnClickListener(this)
        queryData.setOnClickListener(this)
        replaceData.setOnClickListener(this)

        dbHelper = MyDatabaseHelper(this, "BookStore.db", 3)

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    @SuppressLint("Range")
    override fun onClick(v: View?) {
        when(v){
            createDatabase->{
                dbHelper.writableDatabase
            }
            addData->{
                val db = dbHelper.writableDatabase
                val values1 = ContentValues().apply {
                    // 开始组装第一条数据
                    put("name", "The Da Vinci Code")
                    put("author", "Dan Brown")
                    put("pages", 454)
                    put("price", 16.96)
                }
                db.insert("Book", null, values1) // 插入第一条数据
                val values2 = ContentValues().apply {
                    // 开始组装第二条数据
                    put("name", "The Lost Symbol")
                    put("author", "Dan Brown")
                    put("pages", 510)
                    put("price", 19.95)
                }
                db.insert("Book", null, values2) // 插入第二条数据
            }
            updateData->{
                val db = dbHelper.writableDatabase
                val values = ContentValues()
                values.put("price", 10.99)
                db.update("Book", values, "name = ?", arrayOf("The Da Vinci Code"))
            }
            deleteData->{
                val db = dbHelper.writableDatabase
                db.delete("Book", "pages > ?", arrayOf("500"))
            }
            queryData->{
                val db = dbHelper.writableDatabase
                // 查询Book表中所有的数据
                val cursor = db.query("Book", null, null, null, null, null, null)
                if (cursor.moveToFirst()) {
                    do {
                        // 遍历Cursor对象，取出数据并打印
                        val name = cursor.getString(cursor.getColumnIndex("name"))
                        val author = cursor.getString(cursor.getColumnIndex("author"))
                        val pages = cursor.getInt(cursor.getColumnIndex("pages"))
                        val price = cursor.getDouble(cursor.getColumnIndex("price"))
                        Log.d("MainActivity", "book name is $name")
                        Log.d("MainActivity", "book author is $author")
                        Log.d("MainActivity", "book pages is $pages")
                        Log.d("MainActivity", "book price is $price")
                    } while (cursor.moveToNext())
                }
                cursor.close()
            }
            replaceData->{
                val db = dbHelper.writableDatabase
                db.beginTransaction() // 开启事务
                try {
                    db.delete("Book", null, null)
//                    if (true) {
//                        // 手动抛出一个异常，让事务失败
//                        throw NullPointerException()
//                    }
                    val values = ContentValues().apply {
                        put("name", "Game of Thrones")
                        put("author", "George Martin")
                        put("pages", 720)
                        put("price", 20.85)
                    }
                    db.insert("Book", null, values)
                    db.setTransactionSuccessful() // 事务已经执行成功
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    db.endTransaction() // 结束事务
                }
            }
        }
    }
}